package distribution;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SchemeItem {

	private List<Integer> codes;
	private long bitCode;

	/**
	 * codes中包含的数据必须在指定范围内，并且正序排列
	 * 
	 * @param codes
	 * @param count
	 */
	public SchemeItem(List<Integer> codes) {
		super();
		this.codes = codes;
		createBitCode();
	}

	public List<Integer> getCodes() {
		return codes;
	}

	public void setCodes(List<Integer> codes) {
		this.codes = codes;
	}

	private void createBitCode(){
		bitCode = 0;
		if(codes!=null && codes.size() > 0){
			for(Integer c : codes){
				bitCode |= 1 << (c-1);
			}
		}
	}
	
	public int matchCount(SchemeItem si) {
		int count = 0;
		Map<Integer, Integer> mm = new HashMap<Integer, Integer>();
		if (getCodes() != null && getCodes().size() > 0) {
			for (Integer c : getCodes()) {
				mm.put(c, c);
			}
			if (si != null && si.getCodes() != null && si.getCodes().size() > 0) {
				for (Integer c : si.getCodes()) {
					if (mm.get(c) != null) {
						count++;
					}
				}
			}
		}
		return count;
	}
	
	public boolean bitMatchNone(SchemeItem si){
		return (this.bitCode & si.bitCode) == 0;
	}
	
	public int bitMatchCount(SchemeItem si) {
		int count = 0;
		if(si!=null){
			count = Long.bitCount(this.bitCode & si.bitCode);
		}
		return count;
	}

	/**
	 * 两个方案是否匹配
	 * 
	 * @param si
	 * @return
	 */
	public boolean matchAll(SchemeItem si) {
		if (this.getCount() == matchCount(si)) {
			return true;
		}
		return false;
	}

	public boolean contain(Integer[] cs) {
		if (cs != null && cs.length > 0 && this.codes != null
				&& this.codes.size() > 0) {
			for (Integer cc : cs) {
				boolean contain = false;
				for (Integer code : this.codes) {
					if (cc.equals(code)) {
						contain = true;
					}
				}
				if (!contain) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

	@Override
	public String toString() {
		StringBuilder b = new StringBuilder();
		for (int i = 0;; i++) {
			b.append(String.valueOf(codes.get(i)));
			if (i == codes.size() - 1)
				return b.toString();
			b.append("\t");
		}
	}

	public int getCount() {
		return codes == null ? 0 : codes.size();
	}

	public long getBitCode() {
		return bitCode;
	}
	
}
